package com.cyan.app.workflow.activity.WHM;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.activity.SFC.GdlkCkActivity;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.CommonBean;
import com.cyan.app.workflow.bean.Invbat2LabBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;

/**
 * Created by DXW on 2017/10/30.
 */
public class CkDbSubActivity extends BaseActivity {
    private EditText mEditTextUser;
    private Button mButtonUser;
    private Button mButtonSubmit;
    private EditText mEditTextFixnr;
    private EditText mEditTextCk;
    private static final String USERNO = "WHM_DB_USERNO";
    private ShowTipDialog showdialog = new ShowTipDialog();
    private ArrayList<Invbat2LabBean.Invbat2Bean> mInvbat2BeanList;
    private static final String WAREH = "WHM_DB_WAREH";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whm_ck_sub);
        mInvbat2BeanList = (ArrayList<Invbat2LabBean.Invbat2Bean>) getIntent().getSerializableExtra("ck_db_detail");
        titleBar();
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //人员扫描
        if (requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if (data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("40010")) {
                AppUtils.showTip(CkDbSubActivity.this, "工号不存在");
            } else {
                String pisUser = result.substring(5);
                ;
                mEditTextUser.setText(pisUser);
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(USERNO, pisUser).commit();
            }
        }
        //库位扫描
        if (requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if (data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("30010")) {
                AppUtils.showTip(CkDbSubActivity.this, "库位不存在");
            } else {
                mEditTextFixnr.setText(String.valueOf(result.substring(5)));
            }
        }
        //仓库选择
        if (requestCode == 0x0004 && resultCode == RESULT_OK) {
            String result = "";
            if (data != null) {
                result = data.getStringExtra("wareh");
                mEditTextCk.setText(String.valueOf(result));
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(WAREH, result).commit();
            }
        }
    }
    //初始化标题
    private void titleBar() {
        TextView mTitleName = (TextView) findViewById(R.id.top_title_info);
        mTitleName.setText("调拨");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
    }
    //初始化试图
    private void initView() {
        mEditTextCk = (EditText) findViewById(R.id.whm_ck_sub_wareh);
        mEditTextCk.setInputType(InputType.TYPE_NULL);
        String wareh = PreferenceManager.getDefaultSharedPreferences(this).getString(WAREH, null);
        if (wareh != null) {
            mEditTextCk.setText(String.valueOf(wareh));
        }
        Button mButtonCk = (Button) findViewById(R.id.whm_ck_sub_wareh_sm);
        mButtonCk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(CkDbSubActivity.this, GdlkCkActivity.class);
                startActivityForResult(intent, 0x0004);
            }
        });

        mEditTextFixnr = (EditText) findViewById(R.id.whm_ck_sub_fixnr);
        Button mButtonFixnr = (Button) findViewById(R.id.whm_ck_sub_fixnr_sm);
        mButtonFixnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(CkDbSubActivity.this, CaptureActivity.class), 0x0001);
            }
        });
        mEditTextUser = (EditText) findViewById(R.id.whm_ck_sub_user);
        mEditTextUser.setInputType(InputType.TYPE_NULL);;
        String ygbh = PreferenceManager.getDefaultSharedPreferences(this).getString(USERNO, null);
        if (ygbh != null) {
            mEditTextUser.setText(String.valueOf(ygbh));
        }
        mButtonUser = (Button) findViewById(R.id.whm_ck_sub_user_sm);
        mButtonUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(CkDbSubActivity.this, CaptureActivity.class), 0x0002);
            }
        });
        mButtonSubmit = (Button) findViewById(R.id.whm_ck_sub_submit);
        mButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditTextCk.getText().toString().isEmpty()) {
                    AppUtils.showTip(CkDbSubActivity.this, "仓库不能为空");
                    return;
                }
                if (mEditTextUser.getText().toString().isEmpty()) {
                    AppUtils.showTip(CkDbSubActivity.this, "送检人员不能为空");
                    return;
                }

                if (mEditTextFixnr.getText().toString().isEmpty()) {
                    AppUtils.showTip(CkDbSubActivity.this, "库位不能为空");
                    return;
                }
                new submitAsyncLoader().execute(
                        mEditTextFixnr.getText().toString()
                        ,mEditTextUser.getText().toString()
                        ,mEditTextCk.getText().toString()
                );
            }
        });
    }

    public class submitAsyncLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            showdialog.showDialog(CkDbSubActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            String action = HttpConfig.HTTP_MAIN_SERVER_ACTION_324;
            try {
                JSONArray arrays = new JSONArray();
                for (Invbat2LabBean.Invbat2Bean bean: mInvbat2BeanList){
                    JSONObject obj = new JSONObject();
                    obj.put("FromWareh",bean.getWareh());
                    obj.put("FromFixnr",bean.getFixnr());
                    obj.put("Itnbr",bean.getItnbr());
                    obj.put("FromVarnr",bean.getVarnr());
                    obj.put("ToVarnr",bean.getVarnr1());
                    obj.put("Onhand1",bean.getOnhand2());
                    arrays.put(obj);
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ToFixnr", params[0]);
                jsonObject.put("Userno", params[1]);
                jsonObject.put("ToWareh", params[2]);
                jsonObject.put("OperationType", "310");
                jsonObject.put("DbDetails", arrays);
                result = GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, action, jsonObject.toString(), getApplicationContext());
            } catch (Exception e) {
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s == null || s.isEmpty() || s.contains("html")) {
                AppUtils.showTip(CkDbSubActivity.this, "操作异常，请稍后再试！");
                showdialog.closeDialog();
                return;
            }
            CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
            if (commonBean.getCode() == 1) {
                CkDbSubActivity.this.setResult(RESULT_OK);
                AppUtils.showTip(CkDbSubActivity.this, "作业成功。");
                showdialog.closeDialog();
                finish();
            } else {
                CkDbSubActivity.this.setResult(RESULT_CANCELED);
                AppUtils.showTip(CkDbSubActivity.this, "作业失败，" + commonBean.getMsg());
                showdialog.closeDialog();
            }
        }
        protected void onCancelled(String s) {
            CkDbSubActivity.this.setResult(RESULT_CANCELED);
        }
    }
}
